<?php

/**
 * Class My_Application
 */
abstract class My_Application extends Core_Application {

    public $ApiLog = true;
    public static $userid = 0;

    public function __construct(Core_Request $request) {
        parent::__construct($request);

        if (Core_Dispatcher::$forward_ct > 1) {
            return;
        }

        Core_Vo::registerOutputFilter([$this, 'jsonOutWrapper']);
        mb_internal_encoding('utf-8');
        Core_Timer::timer('api');
        //init My_Request
        My_Request::getInstance();

        if ($this->ApiLog) {

            Core_Context::register(Core_Context::AFTER_DISPATCH, function () use ($request) {
                try {
                    $log = new stdclass();
                    $log->userid = Lib_Token::getUserId();
                    $log->submit = $request->getParam('submit') . ' [' . $request->getCmd() . ']';
                    $log->param = json_encode($request->getParams(), JSON_UNESCAPED_UNICODE);
                    $log->duration = Core_Timer::timer('api');
                    $rsp = Core_Context::$response;
                    $log->ok = $rsp['OK'];
                    $log->debug = '';
                    if ($log->ok != 0) {
                        $log->debug = json_encode($rsp, JSON_UNESCAPED_UNICODE);
                    }
                    $log->ipaddr = Lib_Util::getRemoteAddr();
                    $log->sess = '';
                    $log->ver = $request->getParam('v');
                    $log->chan = $request->getParam('vc');
                    $log->UDID = $request->getParam('vd');
                    $log->timestamp = $_SERVER['REQUEST_TIME'];
                    // stats
                    $log->dbqcnt = Core_Stats::$dbQueryCnt;
                    $log->mccnt = Core_Stats::$memcacheCnt;
                    $log->mongocnt = Core_Stats::$mongoQueryCnt;
                    //todo
                    $log->rediscnt = 0;

                    $log->memory = memory_get_peak_usage();
                    $log->include = count(get_included_files());

                    $exclude = ['search/getHotwords', 'search/getHotTags'];
                    if (!in_array($request->getCmd(), $exclude)) {
                        Core_Redis::getInstance('log')->rPush("submitlog", json_encode($log, JSON_UNESCAPED_UNICODE));
                    }

                    if (Core_Config::get('statsLog')) {
                        Core_Log::log($log, 'stats');
                    }

                    $arr = [
                        $log->userid,
                        $request->getParam('submit'),
                        $request->getCmd(),
                        $log->timestamp,
                        $log->duration,
                        $log->ipaddr,
                        $log->ver,
                        $log->chan,
                        $log->UDID,
                        $log->dbqcnt,
                        $log->mccnt,
                        $log->mongocnt,
                        $log->memory,
                        $log->include,
                        $log->param
                    ];
                    Core_Log::log(implode("\t", $arr), 'API_CALL');
                } catch (Exception $e) {
                    //hehe just ignore
                }

            });

        }
    }

    /**
     * @param       $cmd
     * @param array $params
     * @return mixed
     */
    public function call($cmd, $params = []) {
        return Core_Context::call($cmd, $params);
    }

    public function jsonOutWrapper($data) {
        if (is_string($data)) {
            return [
                'OK' => 0,
                'msg' => $data
            ];
        } else {
            if (is_array($data) && isset($data['obj'])) {
                return [
                    'OK' => 0,
                    'obj' => $data['obj']
                ];
            } else {
                return [
                    'OK' => 0,
                    'obj' => $data
                ];
            }
        }
    }
}